<template>
  <div class="order-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>商品列表</h2>
        </div>
      </template>

      <!-- 商品列表 -->
      <el-table :data="products" style="width: 100%" border>
        <el-table-column prop="name" label="商品名称" width="180" />
        <el-table-column prop="price" label="单价" width="120">
          <template #default="scope">
            {{ formatPrice(scope.row.price) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
                size="small"
                @click="addToCart(scope.row)"
                :disabled="scope.row.stock <= 0"
            >
              {{ scope.row.stock <= 0 ? '已售罄' : '加入订单' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="box-card cart-section">
      <template #header>
        <div class="card-header">
          <h2>订单信息</h2>
        </div>
      </template>

      <!-- 购物车/订单列表 -->
      <el-table :data="cart" style="width: 100%" border>
        <el-table-column prop="name" label="商品名称" width="180" />
        <el-table-column prop="price" label="单价" width="120">
          <template #default="scope">
            {{ formatPrice(scope.row.price) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120">
          <template #default="scope">
            <el-input-number
                v-model="scope.row.quantity"
                :min="1"
                :max="scope.row.stock"
                @change="updateCart"
            />
          </template>
        </el-table-column>
        <el-table-column label="小计" width="120">
          <template #default="scope">
            {{ formatPrice(scope.row.price * scope.row.quantity) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                @click="removeFromCart(scope.$index)"
                circle
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="total-price">
        <h3>总价: {{ formatPrice(totalPrice) }}</h3>
      </div>

      <!-- 订单表单 -->
      <el-form
          :model="orderForm"
          :rules="rules"
          ref="orderFormRef"
          label-width="100px"
          class="order-form"
      >
        <el-form-item label="收货人" prop="receiver">
          <el-input v-model="orderForm.receiver" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="orderForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input
              v-model="orderForm.address"
              type="textarea"
              :rows="2"
              placeholder="请输入详细收货地址"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="orderForm.remarks"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息"
          />
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="submitOrder"
              :disabled="cart.length === 0"
          >
            提交订单
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import {axiosGet} from "@/utils/axios-utils.js";

// 商品数据
const products = ref([])

// 购物车数据
const cart = ref([])

// 订单表单
const orderForm = ref({
  receiver: '',
  phone: '',
  address: '',
  remarks: ''
})

// 表单验证规则
const rules = {
  receiver: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ]
}

onMounted(()=>{
  axiosGet('api/product')
      .then(ret=>{
        if(ret.code == 'ok'){
          products.value = ret.data
        }
      })
})

// 计算总价
const totalPrice = computed(() => {
  return cart.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
})

// 格式化价格显示
const formatPrice = (price) => {
  return '¥' + price.toFixed(2)
}

// 添加商品到购物车
const addToCart = (product) => {
  const existingItem = cart.value.find(item => item.id === product.id)

  if (existingItem) {
    if (existingItem.quantity < product.stock) {
      existingItem.quantity++
      ElMessage.success(`已增加 ${product.name} 数量`)
    } else {
      ElMessage.warning(`已达到 ${product.name} 的最大库存`)
    }
  } else {
    cart.value.push({
      ...product,
      quantity: 1
    })
    ElMessage.success(`已添加 ${product.name} 到订单`)
  }

  // 更新商品库存显示
  updateProductStock()
}

// 从购物车移除商品
const removeFromCart = (index) => {
  const removedItem = cart.value.splice(index, 1)[0]
  ElMessage.success(`已移除 ${removedItem.name}`)
  updateProductStock()
}

// 更新购物车后同步商品库存显示
const updateProductStock = () => {
  products.value.forEach(product => {
    const cartItem = cart.value.find(item => item.id === product.id)
    if (cartItem) {
      product.stock = cartItem.originalStock - cartItem.quantity
    }
  })
}

// 购物车数量变化时更新
const updateCart = () => {
  updateProductStock()
}

// 提交订单
const submitOrder = () => {
  orderFormRef.value.validate((valid) => {
    if (valid) {
      const orderData = {
        ...orderForm.value,
        items: cart.value.map(item => ({
          productId: item.id,
          name: item.name,
          price: item.price,
          quantity: item.quantity
        })),
        totalPrice: totalPrice.value,
        orderTime: new Date().toISOString()
      }

      // 这里应该是发送到后端API
      console.log('提交订单:', orderData)

      ElMessageBox.confirm(
          `确认提交订单? 总金额: ${formatPrice(totalPrice.value)}`,
          '订单确认',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        // 模拟API调用
        setTimeout(() => {
          ElMessage.success('订单提交成功!')
          resetForm()
          cart.value = []
        }, 1000)
      }).catch(() => {
        ElMessage.info('已取消订单')
      })
    } else {
      ElMessage.error('请填写完整的订单信息')
    }
  })
}

// 重置表单
const resetForm = () => {
  orderFormRef.value.resetFields()
}

// 表单引用
const orderFormRef = ref(null)
</script>

<style scoped>
.order-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-section {
  margin-top: 30px;
}

.total-price {
  margin: 20px 0;
  text-align: right;
  padding-right: 20px;
}

.order-form {
  margin-top: 30px;
}

.el-input-number {
  width: 100px;
}
</style>